import bq.service.Service;

import java.util.ArrayList;

public abstract class Controller<T> implements Service<T> {

    @Override
    public void insert(T data, ArrayList<T> items) {
        items.add(data);
        System.out.println("添加成功！");
    }

    @Override
    public void delete(int index, ArrayList<T> items) {
        try {
            items.remove(index-1);
            System.out.println("删除成功! ");
        }catch (IndexOutOfBoundsException e) {
            System.out.println("删除失败！");
        }
    }

    @Override
    public void update(T data, ArrayList<T> items) {
        if (!items.isEmpty()) {
            for (int i = 0;i < items.size();i++) {
                if ((data instanceof Film) &&
                        ((Film) items.get(i)).getId().equals(((Film) data).getId())) {
                    items.remove(i);
                    items.add(i, data);
                    System.out.println("修改成功!");
                    break;
                }else if ((data instanceof User) && ((User) items.get(i)).getId().equals(((User) data).getId())) {
                    items.remove(i);
                    items.add(i, data);
                    System.out.println("修改成功!");
                    break;
                }
            }
        }else System.out.println("系统中无此元素，请检查!");
    }

    @Override
    public ArrayList<T> selectById(Integer id, ArrayList<T> items) {
        ArrayList<T> items2 = new ArrayList<>();
        for (T item: items) {
            if ((item instanceof Film) && ((Film) item).getId().equals(id)) {
                items2.add(item);
            } else if ((item instanceof User) && ((User) item).getId().equals(id)) {
                items2.add(item);
            }
        }
        return items2;
    }

    @Override
    public ArrayList<T> selectByName(String name, ArrayList<T> items) {
        ArrayList<T> items2 = new ArrayList<>();
        for (T item: items) {
            if ((item instanceof Film) && ((Film) item).getName().equals(name)) {
                items2.add(item);
            } else if ((item instanceof User) && ((User) item).getName().equals(name)) {
                items2.add(item);
            }
        }
        return items2;
    }

    public abstract ArrayList<T> selectAll();
}
